<template>
  <div class="app-container">
    <div class="block">
      <el-row :gutter="20" v-permission="['/car/company']">
        <el-col :span="6">
          <el-input v-model="listQuery.name" placeholder="班次名称"></el-input>
        </el-col>
        <el-col :span="6">
          <el-select v-model="listQuery.state" placeholder="请选择审核状态">
            <el-option
              v-for="item in stateList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button
            type="success"
            icon="el-icon-search"
            @click.native="search"
            >{{ $t("button.search") }}</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-refresh"
            @click.native="reset"
            >{{ $t("button.reset") }}</el-button
          >
        </el-col>
      </el-row>
      <br />
      <div class="block">
        <el-button
          type="success"
          icon="el-icon-plus"
          @click.native="addShift"
          v-permission="['/car/company']"
          >{{ $t("button.add") }}</el-button
        >
      </div>
      <div class="table_container" v-permission="['/business/shop/audit']">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form
                label-position="left"
                inline
                class="demo-table-expand"
                label-width="120px"
              >
                <el-form-item label="班次名称">
                  <span>{{ props.row.name }}</span>
                </el-form-item>
                <el-form-item label="所属路线">
                  <span>{{ props.row.companyId }}</span>
                </el-form-item>
                <el-form-item label="介绍">
                  <span>{{ props.row.description }}</span>
                </el-form-item>
                <el-form-item label="发车时间">
                  <span>{{ props.row.start }}</span>
                </el-form-item>
                <el-form-item label="终点">
                  <span>{{ props.row.end }}</span>
                </el-form-item>
                <!-- <el-form-item label="线路 ID">
                  <span>{{ props.row.id }}</span>
                </el-form-item> -->
                <el-form-item label="联系电话">
                  <span>{{ props.row.phone }}</span>
                </el-form-item>
                <el-form-item label="班次">
                  <span>{{ props.row.rating }}</span>
                </el-form-item>
                <!-- <el-form-item label="销售量">
                  <span>{{ props.row.recent_order_num }}</span>
                </el-form-item> -->
                <!-- <el-form-item label="分类">
                  <span>{{ props.row.category }}</span>
                </el-form-item> -->
                <el-form-item label="分类">
                  <span>{{
                    props.row.end === "火车站" ? "校内" : "校外"
                  }}</span>
                </el-form-item>
                <el-form-item label="审批状态">
                  <span>{{ props.row.stateStr }}</span>
                </el-form-item>
                <el-form-item label="审批结果">
                  <span>{{ props.row.auditRemark }}</span>
                </el-form-item>
                <!-- <el-form-item label="未结算交易额(元)">
                  <span>{{ props.row.unliquidatedAmount }}</span>
                </el-form-item>
                <el-form-item label="已结算交易额(元)">
                  <span>{{ props.row.totalAmount }}</span>
                </el-form-item>
                <el-form-item label="平台收取费率(%)">
                  <span>{{ props.row.platform_rate }}</span>
                </el-form-item> -->
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="班次名称" prop="name"> </el-table-column>
          <el-table-column label="所属线路" prop="address"> </el-table-column>
          <!-- <el-table-column label="线路介绍" prop="description"></el-table-column> -->
          <el-table-column label="操作" width="450">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.state == '0'"
                size="mini"
                type="primary"
                v-permission="['/business/shop/audit']"
                @click="handleAudit(scope.$index, scope.row)"
                >审核
              </el-button>
              <el-button
                size="mini"
                type="warning"
                v-permission="['/car/company']"
                @click="handleCheck(scope.$index, scope.row)"
                >结算
              </el-button>
              <el-button
                v-if="scope.row.disabled == 0"
                size="mini"
                type="danger"
                v-permission="['/business/shop/audit']"
                @click="handleStop(scope.$index, scope.row, 1)"
                >停用
              </el-button>
              <el-button
                v-if="scope.row.disabled == 1"
                size="mini"
                type="primary"
                v-permission="['/business/shop/audit']"
                @click="handleStop(scope.$index, scope.row, 0)"
                >启用
              </el-button>
              <el-button
                size="mini"
                type="primary"
                v-permission="['/business/shop/edit']"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑
              </el-button>
              <el-button
                size="mini"
                type="success"
                v-permission="['/business/food/edit']"
                @click="addFood(scope.$index, scope.row)"
                >添加路线
              </el-button>
              <el-button
                size="mini"
                type="info"
                @click="viewFood(scope.$index, scope.row)"
                >查看路线
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100, 500]"
          :page-size="listQuery.limit"
          :total="total"
          @size-change="changeSize"
          @current-change="fetchPage"
          @prev-click="fetchPrev"
          @next-click="fetchNext"
        >
        </el-pagination>
      </div>

      <el-dialog title="路线审核" :visible.sync="audit.show" width="30%">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入拒绝原因"
          v-model="audit.auditRemark"
        >
        </el-input>
        <span slot="footer" class="dialog-footer">
          <el-button type="danger" @click="handleAuditConfirm(-1)"
            >拒绝</el-button
          >
          <el-button type="primary" @click="handleAuditConfirm(1)"
            >通过</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getApiUrl } from "@/utils/utils";
// import { getToken } from "@/utils/auth";
import { cityGuess } from "@/api/getData";
import permission from "@/directive/permission/index.js";
import {
  getRoutes,
  getResturantsCount,
  foodCategory,
  updateResturant,
  stopResturant,
  auditResturant,
  deleteResturant,
  check
} from "@/api/carservice/routes";

export default {
  directives: { permission },
  data() {
    return {
      // city: {},
      // count: 0,
      fileMgrUrl: getApiUrl() + "/file",
      uploadHeaders: {
        Authorization: ""
      },
      tableData: [],
      currentPage: 1,
      selectTable: {},
      dialogFormVisible: false,
      categoryOptions: [],
      selectedCategory: [],
      address: {},
      total: 0,
      stateList: [
        { label: "审核中", value: "0" },
        { label: "审核通过", value: "1" },
        { label: "审核拒绝", value: "-1" }
      ],
      audit: { show: false, auditRemark: "" },
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        state: ""
      },
      routeId: 0
    };
  },
  created() {
    this.initData();
    this.routeId = this.$route.query.routeId;
    // this.uploadHeaders["Authorization"] = getToken();
  },

  methods: {
    async initData() {
      this.fetchListData();
    },
    async getCategory() {
      try {
        const response = await foodCategory();
        const categories = response.data;
        categories.forEach(item => {
          if (item.sub_categories.length) {
            const addnew = {
              value: item.name,
              label: item.name,
              children: []
            };
            item.sub_categories.forEach((subitem, index) => {
              if (index === 0) {
                return;
              }
              addnew.children.push({
                value: subitem.name,
                label: subitem.name
              });
            });
            this.categoryOptions.push(addnew);
          }
        });
      } catch (err) {
        console.log("获取商铺种类失败", err);
      }
    },
    async fetchListData() {
      console.log(this.$route.query.routeId);
      // getRoutes().then(res => {
      //   console.log(res);
      //   const restaurants = res;
      //   this.total = res.length;
      //   console.log(this.total);
      //   restaurants.forEach(item => {
      //     const tableData = {};
      //     tableData.name = item.routeId;
      //     tableData.address = item.companyId;
      //     tableData.companyId = item.companyId;
      //     tableData.description = item.description;
      //     tableData.start = item.start;
      //     tableData.end = item.end;
      //     tableData.id = item.id;
      //     tableData.phone = item.phone;
      //     tableData.rating = item.rating;
      //     tableData.recent_order_num = item.recent_order_num;
      //     tableData.category = item.category;
      //     tableData.image_path = item.image_path;
      //     tableData.state = item.state;
      //     tableData.stateStr = item.status;
      //     tableData.auditRemark = item.auditRemark;
      //     tableData.disabled = item.disabled;
      //     tableData.unliquidatedAmount = item.unliquidatedAmount;
      //     tableData.totalAmount = item.totalAmount;
      //     tableData.isInSchool = item.isInSchool + "";
      //     tableData.platform_rate = item.platform_rate;
      //     this.tableData.push(tableData);
      //     this.shopDetail = tableData;
      //   });
      // });
    },
    async fetchData() {
      getResturants(this.listQuery).then(response => {
        const restaurants = response.data.records;
        this.total = response.data.total;
        this.tableData = [];
        restaurants.forEach(item => {
          const tableData = {};
          tableData.name = item.name;
          tableData.address = item.address;
          tableData.description = item.description;
          tableData.id = item.id;
          tableData.phone = item.phone;
          tableData.rating = item.rating;
          tableData.recent_order_num = item.recent_order_num;
          tableData.category = item.category;
          tableData.image_path = item.image_path;
          tableData.state = item.state;
          tableData.stateStr = item.stateStr;
          tableData.auditRemark = item.auditRemark;
          tableData.disabled = item.disabled;
          tableData.unliquidatedAmount = item.unliquidatedAmount;
          tableData.totalAmount = item.totalAmount;
          tableData.isInSchool = item.isInSchool + "";
          tableData.platform_rate = item.platform_rate;
          this.tableData.push(tableData);
          this.shopDetail = tableData;
        });
      });
    },

    search() {
      this.fetchData();
    },
    reset() {
      this.listQuery.name = "";
      this.listQuery.state = "";
      this.fetchData();
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.offset = (val - 1) * this.limit;
      this.getResturants();
    },
    fetchNext() {
      this.listQuery.page = this.listQuery.page + 1;
      this.fetchData();
    },
    fetchPrev() {
      this.listQuery.page = this.listQuery.page - 1;
      this.fetchData();
    },
    fetchPage(page) {
      this.listQuery.page = page;
      this.fetchData();
    },
    changeSize(limit) {
      this.listQuery.limit = limit;
      this.fetchData();
    },
    handleStop(index, row, disabled) {
      let me = this;
      this.$confirm("确认" + (disabled == 1 ? "停用商铺" : "启用商铺") + "?", {
        confirmButtonText: "确认",
        cancelButtonText: "取消"
      })
        .then(({ value }) => {
          stopResturant({ id: row.id, disabled: disabled }).then(response => {
            this.$message({
              type: "success",
              message: (disabled == 1 ? "停用商铺" : "启用商铺") + "成功"
            });
            me.fetchData();
          });
        })
        .catch(({ value }) => {});
    },
    handleAuditConfirm(state) {
      if (state == "-1") {
        if (this.audit.auditRemark == "") {
          this.$message({
            type: "warning",
            message: "请输入拒绝原因"
          });
          return;
        }
      }
      const params = {
        id: this.selectTable.id,
        state: state,
        auditRemark: this.audit.auditRemark
      };
      console.log(params);

      auditResturant(params).then(response => {
        this.$message({
          type: "success",
          message: "审核成功"
        });
        this.fetchData();
      });
      this.audit.show = false;
    },
    handleAudit(index, row) {
      this.audit.show = true;
      this.selectTable = row;
    },
    handleCheck(index, row) {
      if (row.unliquidatedAmount == "" || row.unliquidatedAmount == "0") {
        this.$message({
          type: "warning",
          message: "没有可结算的交易额"
        });
        return;
      }
      let me = this;
      this.$confirm("待结算金额" + row.unliquidatedAmount + "元,确认结算?", {
        confirmButtonText: "确认",
        cancelButtonText: "取消"
      })
        .then(({ value }) => {
          check({ id: row.id }).then(response => {
            this.$message({
              type: "success",
              message: "结算成功"
            });
            me.fetchData();
          });
        })
        .catch(({ value }) => {});
    },
    handleEdit(index, row) {
      console.log("row", row);
      this.selectTable = row;
      this.selectTable.image =
        getApiUrl() + "/file/getImgStream?fileName=" + row.image_path;
      this.address.address = row.address;
      this.dialogFormVisible = true;
      this.selectedCategory = row.category.split("/");
      if (!this.categoryOptions.length) {
        this.getCategory();
      }
    },
    addShift() {
      this.$router.push({
        path: "/car/shift/add"
        // query: { restaurant_id: row.id }
      });
    },
    addFood(index, row) {
      this.$router.push({
        path: "/business/food/add",
        query: { restaurant_id: row.id }
      });
    },
    viewFood(index, row) {
      this.$router.push({
        path: "/business/food",
        query: { restaurant_id: row.id }
      });
    },
    async handleDelete(index, row) {
      try {
        const res = await deleteResturant(row.id);
        if (res.status == 1) {
          this.$message({
            type: "success",
            message: "删除店铺成功"
          });
          this.tableData.splice(index, 1);
        } else {
          throw new Error(res.message);
        }
      } catch (err) {
        this.$message({
          type: "error",
          message: err.message
        });
        console.log("删除店铺失败");
      }
    },
    async querySearchAsync(queryString, cb) {
      if (queryString) {
        try {
          const cityList = await searchplace(this.city.id, queryString);
          if (cityList instanceof Array) {
            cityList.map(item => {
              item.value = item.address;
              return item;
            });
            cb(cityList);
          }
        } catch (err) {
          console.log(err);
        }
      }
    },
    addressSelect(vale) {
      const { address, latitude, longitude } = vale;
      this.address = { address, latitude, longitude };
    },
    handleServiceAvatarScucess(res, file) {
      this.selectTable.image_path = res.data.realFileName;
      this.selectTable.image =
        getApiUrl() + "/file/getImgStream?fileName=" + res.data.realFileName;
    },
    beforeAvatarUpload(file) {
      const isRightType =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isRightType) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isRightType && isLt2M;
    },
    async updateShop() {
      this.dialogFormVisible = false;
      try {
        Object.assign(this.selectTable, this.address);
        this.selectTable.category = this.selectedCategory.join("/");
        updateResturant(this.selectTable).then(response => {
          this.$message({
            type: "success",
            message: "更新店铺信息成功"
          });
          this.getResturants();
        });
      } catch (err) {
        console.log("更新餐馆信息失败", err);
        this.$message({
          type: "error",
          message: err
        });
      }
    }
  }
};
</script>

<style lang="less">
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.table_container {
  padding: 20px;
}

.Pagination {
  display: flex;
  justify-content: flex-start;
  margin-top: 8px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
